package com.example.questionnaire.utils;

import android.app.Activity;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewTreeObserver;

/***
 * ********************************************
 *
 * @author YuShuyou
 * @version *********************************************
 * @Description Gbss单例
 * @E-mail:you551@163.com
 * @qq:447234062
 * @date 2016-3-30 下午4:52:34
 */
public class GbssUtils {
    private static GbssUtils gbssUtils;

    public static GbssUtils getInstance(){
        if (gbssUtils==null) {
            //双重检测 ,保证线程安全
            synchronized (GbssUtils.class) {
                if (gbssUtils==null) {
                    gbssUtils=new GbssUtils();
                }
            }
        }
        return gbssUtils;
    }

    public void observeSoftKeyboard(Activity activity, final OnSoftKeyboardChangeListener listener) {
        final View decorView = activity.getWindow().getDecorView();
        decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            int previousKeyboardHeight = -1;
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                decorView.getWindowVisibleDisplayFrame(rect);
                int displayHeight = rect.bottom - rect.top;
                int height = decorView.getHeight();
                int keyboardHeight = height - displayHeight;
                if (previousKeyboardHeight != keyboardHeight) {
                    boolean hide = (double) displayHeight / height > 0.8;
                    listener.onSoftKeyBoardChange(keyboardHeight, !hide);
                }
                previousKeyboardHeight = height;
            }
        });
    }

    public interface OnSoftKeyboardChangeListener {
        void onSoftKeyBoardChange(int softKeybardHeight, boolean visible);
    }
}